package controlleur;

import exceptions.DataSourceException;
import exceptions.EmployeNotFoundException;
import exceptions.LoginException;
import eyrolles.LoginForm;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modele.Employe;
import modele.InterfaceEmployeModel;
import org.apache.struts.action.*;

public class LoginAction extends GenericAction {

    public ActionForward login(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
            throws IOException, ServletException {
        ActionMessages errors = new ActionMessages();
        String user = null;

        // Cible par defaut en cas de succes
        String target = "success";

        // Utilisation de LoginForm pour obtenir les parametres
        // de la requete
        String username = ((LoginForm) form).getUsername();
        String password = ((LoginForm) form).getPassword();

        try {
            InterfaceEmployeModel employeModel = getModel(request);
            Employe employe = employeModel.get(username);
            user = employe.getUsername();

            // Verification du mot de passe
            if (!password.equals(employe.getPassword()))
                throw new LoginException();

        } catch (EmployeNotFoundException e) {
            target = "login";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.login.unknown", username));
        } catch (LoginException e) {
            target = "login";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.login.password", username));
        } catch (DataSourceException e) {
            target = "login";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.database.error", username));
        }

        // Enregistrer les erreurs trouvees dans le formulaire original
        if (errors.isEmpty()) {
            HttpSession session = request.getSession();
            session.setAttribute("USER", user);
        } else
            saveErrors(request, errors);

        // Transmission de la requete a la vue appropriee
        return (mapping.findForward(target));
    }
}